import {
	ref,
	computed,
	watchEffect
} from "vue";
import {
	useStore
} from "vuex";

export function useLabels() {
	const store = useStore();
	const labelIds = ref([]);
	const isEdit = ref(false);

	// 监听 userInfo 变化，同步 labelIds
	watchEffect(() => {
		const userInfo = store.state.userInfo;
		if (userInfo?.label_ids) {
			labelIds.value = [...userInfo.label_ids];
		}
	});

	// 计算属性
	const labelList = computed(() => store.state.labelList);
	const selfLabelList = computed(() => {
		return labelList.value.filter(item => labelIds.value.includes(item._id))
	});
	const recommendList = computed(() => {
		return labelList.value.filter(item => !labelIds.value.includes(item._id) && item._id)
	});

	// 方法
	const _updateLabel = async () => {
		try {
			// 发送后端更新逻辑
			await store.dispatch('updateUserLabels', labelIds.value);
			console.log("标签更新成功");
		} catch (error) {
			console.error("标签更新失败:", error);
		}
	};

	const startEdit = () => {
		if (isEdit.value) {
			_updateLabel();
		}
		isEdit.value = !isEdit.value;
	};

	const addLabel = (item) => {
		if (!isEdit.value) return;
		if (!labelIds.value.includes(item._id)) {
			labelIds.value.push(item._id);
		}
	};

	const removeLabel = (item) => {
		labelIds.value = labelIds.value.filter(id => id !== item._id);
	};

	return {
		// 状态
		labelIds,
		isEdit,

		// 计算属性
		labelList,
		selfLabelList,
		recommendList,

		// 方法
		startEdit,
		addLabel,
		removeLabel
	};
}